package com.wolf.util;

import com.googlecode.jslint4java.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.util.List;

/**
 * javascript工具类
 *
 * @author sdyang
 * @date 2019/12/4 15:29
 **/
public class JavascriptUtil {

    private static Logger logger = LoggerFactory.getLogger(JavascriptUtil.class);

    /**
     * 语法检查
     *
     * @param functionName
     * @param content
     * @return
     */
    public static boolean check(String functionName, String content) {
        JSLintBuilder builder = new JSLintBuilder();

        //使用默认的jslint.js进行初始化
        JSLint jsLint = builder.fromDefault();
        //自定义jslint.js进行初始化

        //过滤的警告选项
        jsLint.addOption(Option.SLOPPY);
        jsLint.addOption(Option.WHITE);
        jsLint.addOption(Option.EQEQ);
        jsLint.addOption(Option.NOMEN);
        jsLint.addOption(Option.CONTINUE);
        jsLint.addOption(Option.REGEXP);
        jsLint.addOption(Option.VARS);
        jsLint.addOption(Option.PLUSPLUS);

        JSLintResult result = jsLint.lint(String.format("%s.js", functionName), content);
        List<Issue> issues = result.getIssues();
        if (issues != null && issues.size() > 0) {
            logger.info(String.format("js文件【%s】总共有%s个问题", functionName, issues.size()));
            for (Issue issue : issues) {
                logger.info(String.format("第%s行的%s出现问题，原因：%s", issue.getLine(),
                        issue.getEvidence(), issue.getReason()));
            }
            return false;
        }
        return true;
    }

    /**
     * 执行
     *
     * @param functionName
     * @param content
     * @param args
     * @return
     */
    public static Object exec(String functionName, String content, Object... args) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("javascript");
        try {
            engine.eval(content);
            if (engine instanceof Invocable) {
                Invocable in = (Invocable) engine;
                return in.invokeFunction(functionName, args);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
